<?php declare(strict_types=1);

namespace App\Bac\Controller;

use App\Abstract\Controller;
use App\Bac\Handler\RBAC\AdminHandler;
use App\Bac\Model\RBAC\Admin as AdminModel;
use App\Bac\Provider\CommonProvider;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Helper\RespHelper;
use App\Service\FileHandler;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;

class HomeController extends Controller
{

    #[Inject]
    protected CommonProvider $provider;

    #[Inject]
    protected AdminHandler $adminHandler;

    public function login(): array
    {
        return $this->adminHandler->login($this->request->all());
    }

    public function logout(): array
    {
        $resp = AdminModel::getCurAdmin()->logout();
        if ($resp) {
            return RespHelper::success();
        }
        return RespHelper::fail();
    }

    public function getAuthor(): array
    {
        $admin = AdminModel::getCurAdmin();
        return RespHelper::success($admin->package());
    }

    public function updatePassword(): array
    {
        return (new AdminModel)->updatePassword($this->request->all());
    }

    /**
     * 首页面板数据
     */
    public function dashboard(): array
    {
        return $this->provider->dashboard();
    }

    public function upload(): array
    {
        $file = $this->request->file('file');
        if (!$file instanceof UploadedFile)
            throw new BusinessException(ErrorCode::ERR_PARAMETER, '上传失败：请提交文件');
        $business = $this->request->input('business');
        if (!in_array($business, ['config', 'prix']))
            throw new BusinessException(ErrorCode::ERR_PARAMETER, '不允许的文件类型');
        $fileReceiver = make(FileHandler::class);
        return $fileReceiver->receiveFile($file, $business);
    }

    /**
     * 清理服务端的数据缓存
     * @return array
     * @throws \RedisException
     */
    public function clearCache(): array
    {
        $redis = getRedis();
        $cacheKeys = $redis->keys('Cache:*');
        $mapCacheKeys = $redis->keys('MapCache:*');
        $redis->del(...array_values(array_unique(array_merge($cacheKeys, $mapCacheKeys))));
        return RespHelper::success();
    }
}